#include "strategies/ExpValueDrawingStrategy.h"
#include "CCardStack.h"

using namespace Card;

bool ExpValueDrawingStrategy::pickFromDiscard(CCardStack* hand, const GameState* gameState) {
    bool decidePick;
    const CCard& topOfDiscard = gameState->getCardsInDiscard().back();
    int discardValue = calculateGain(hand, CCard(topOfDiscard.GetIndex()), true, gameState);
    Query::debugOut(string("Discard value is "), 2);
    Query::debugValue(discardValue, 2);
    if (discardValue > 0) {
        float deckValue = 0;
        int numSmaller = 0;
        CCardStack possibleCards = gameState->getUnknownCards(gameState->getCurrPlayer());
        if (possibleCards.Size() > 0) {
            for (CONST_VI ci = possibleCards.begin(); ci != possibleCards.end(); ci++) {
                int gain = calculateGain(hand, CCard(ci->GetIndex()), false, gameState);
                deckValue += gain;
                if (gain <= discardValue) {
                    numSmaller++;
                }
            }
            deckValue /= possibleCards.Size();
            Query::debugOut(string("Deck value is "), 2);
            Query::debugValue((int) deckValue, 2);
            decidePick = (discardValue >= deckValue);
            if (decidePick) {
                decisionCertainty = (100*numSmaller) / possibleCards.Size();
            }
            else {
                decisionCertainty = (100*(possibleCards.Size() - numSmaller)) / possibleCards.Size();
            }
        }
        else {
            decidePick = true;
            decisionCertainty = 100;
        }
    }
    else {
        decidePick = false;
        decisionCertainty = 100;
    }
    Query::debugOut(string("Decision certainty "), 2);
    Query::debugValue(decisionCertainty, 2);
    return decidePick;
}

int ExpValueDrawingStrategy::calculateGain(CCardStack* hand, const CCard& card, bool picked, const GameState* gameState) {
    int ret = 0;
    if (discardStrategy != NULL) {
        hand->Push(card);
        int discardDecision = discardStrategy->pickDiscard(hand, picked, gameState);
        hand->Pop();
        ret = Query::gainFromCard(*hand, card, discardDecision);
    }
    else {
        Query::debugOut(string("Discard strategy not set for EVDS"), 1);
    }
    return ret;
}
